let {
	Engine,
	Scene,
	RotatePerspectiveCamera,
	Skybox,
	Geometry
} = require("./g3d.min.js") 
 
let lx = null,
	ly = null;
class ImageAr {
 
	/**
	 * @param {Object} selector
	 * @param {Object} canvas
	 * @param {Object} images
	 * @param {Object} opt
	 */
	constructor(canvas, images, opt) {
		this.canvas = canvas;
		// this.gl = canvas.getContext('webgl');
		this.images = images;
		this.opt = opt || {
			//贴图全部加载完成的回调事件
			textureComplete: (image360) => {}
		}
		this.init();
	}
 
	/** 
	 * 初始化 
	 */
	init() {
		let self = this;
		
		this.engine = new Engine(self.canvas);
		this.scene = new Scene(this.engine);
 
		this.camera = new RotatePerspectiveCamera(this.scene);
		 //横向角度
		this.camera.alpha = 0;
		//纵向角度
		this.camera.beta = 0;
		this.camera.radius = 10;
		this.camera.near = 0.001;
		this.camera.far = 2000;
		let cnt = 0; 
		// fbudlr 
		let imageListPOsi = [ "back","front", "top","bottom", "left", "right"];  // 注意图片顺序 后, 前, 上, 下, 左, 右
 
		let pos = {}
		for (let i = 0; i < this.images.length; i++) {
			let image = this.canvas.createImage(); //和h5区别 小程序这里没有 new Image
			pos[imageListPOsi[i]] = image;
			image.onload = () => {
				cnt++;
				if (cnt >= 6) { //pano形式最多6张,也就是正方体的6个面 
					let skybox = new Skybox(self.scene, pos,100,true);
					function render() {
						self.scene.render();
						self.requestAnimationFrame(render);
					}
 
					render();
 
					//贴图全部加载完成后的回调,外部调用
					self.opt.textureComplete && self.opt.textureComplete(self);
				}
			}
			image.src = this.images[i];
		}
	}
 
 
	touchmove(e) {
		let self = this;
		let x = e.touches[0].clientX;
		let y = e.touches[0].clientY;
 
		self.camera.alpha += (x - lx) / 5;
		this.camera.beta = self.clamp(-90, 90, this.camera.beta - (y - ly) / 5); 
		lx = x;
		ly = y;
	}
 
	touchstart(e) {
		let self = this;
		let x = e.touches[0].clientX;
		let y = e.touches[0].clientY;
		lx = x;
		ly = y;
	}
 
	touchend(e) {
 
	}
 
	/**
	 * 重绘界面 就认为是动画呈现吧
	 * 见 https://developers.weixin.qq.com/miniprogram/dev/api/canvas/Canvas.requestAnimationFrame.html
	 */
	requestAnimationFrame(cb) {
		this.canvas.requestAnimationFrame(cb);
	}
 
	clamp(min, max, v) {
		return v < min ? min : v > max ? max : v;
	}
}
 
 
export default ImageAr